<?php
class Appconfig extends CI_Model 
{
	function exists($key)
	{
		$this->db->from('app_config');	
		$this->db->where('app_config.key',$key);
		$query = $this->db->get();
		
		return ($query->num_rows()==1);
	}
	
	function get_store_config()
	{
		$this->db->from('stores');
		$this->db->where('store_id', $this->session->userdata('store_id'));
		$query = $this->db->get();

		if($query->num_rows()==1)
		{
			return $query->row();
		}
		else
		{
			//Get empty base parent object, as $item_id is NOT an item
			$item_obj=new stdClass();

			//Get all the fields from items table
			$fields = $this->db->list_fields('stores');

			foreach ($fields as $field)
			{
				$item_obj->$field='';
			}

			return $item_obj;
		}
	}
	
	function get_all()
	{
		$this->db->from('app_config');
		$this->db->order_by("key", "asc");
		return $this->db->get();		
	}
	
	function get($key)
	{
		$this->db->select($key);
		$this->db->from('stores');	
		$this->db->where('store_id',$this->session->userdata('store_id'));
		$query = $this->db->get();
		
		//$query = $this->db->get_where('app_config', array('key' => $key), 1);
		
		if($query->num_rows()==1)
		{
			return $query->row()->$key;
		}
		
		return "";
		
	}
	
	function save($key,$value)
	{
		$config_data=array(
		'key'=>$key,
		'value'=>$value
		);
				
		if (!$this->exists($key))
		{
			return $this->db->insert('app_config',$config_data);
		}
		
		$this->db->where('key', $key);
		return $this->db->update('app_config',$config_data);		
	}
	
	function batch_save($data)
	{
		$this->db->where('store_id', $this->session->userdata('store_id'));
		return $this->db->update('stores',$data);
	}
		
	function delete($key)
	{
		return $this->db->delete('app_config', array('key' => $key)); 
	}
	
	function delete_all()
	{
		return $this->db->empty_table('app_config'); 
	}
	
	function get_logo_image()
	{
		if ($this->config->item('company_logo'))
		{
			return site_url('app_files/view/'.$this->get('company_logo'));
		}
		return 'images/header/header_logo.png';
	}
		
	function get_additional_payment_types()
	{
		$return = array();
		$payment_types = $this->get('additional_payment_types');
		
		if ($payment_types)
		{
			$return = array_map('trim', explode(',',$payment_types));
		}
		
		return $return;
	}
}

?>